import { downloadInvoiceTemplateApi, importInvoiceApi, importInvoiceToModifyApi } from "@/api/client/documentManagement/waybillManagement";
import CommonHook from "@/hook/commonHook";
import FormHook from "@/hook/formHook";
import { GeneraDataType } from "@/interface";
import { message } from "ant-design-vue";
export default function OperationHook(state: GeneraDataType) {
  const { formState, formDataRef, emit, passData, loading, type } = state;
  const { resetFields } = FormHook({ formState });
  const { downloadFileByUrl } = CommonHook();
  const onFinish = () => {
    const { file, uploadType } = formState;
    const formData = new FormData();
    formData.append("file", file[0].originFileObj);
    formData.append("uploadType", uploadType);
    formData.append("shipmentId", passData.value.id);
    formData.append("path", "parent/");
    loading.value = true;
    let requestFn;
    if (type.value === 1) requestFn = importInvoiceApi;
    else requestFn = importInvoiceToModifyApi;
    requestFn(formData)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          message.success("操作成功!");
          emit("submit", data, uploadType);
        }
      })
      .finally(() => (loading.value = false));
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };
  const resetHandle = () => {
    resetFields();
    formDataRef.value.clearValidate();
    emit("update:visible", false);
  };
  const downloadTemplateHandle = () => {
    return downloadInvoiceTemplateApi({ type: formState.uploadType }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        const fileName = formState.uploadType === 1 ? "导入装箱信息.xlsx" : "导入收件地址与装箱信息.xlsx";
        downloadFileByUrl(data, fileName);
      }
    });
  };
  const uploadRequest = () => {
    formState.file[0].percent = 100;
    formState.file[0].status = "done";
  };
  return {
    onFinish,
    onFinishFailed,
    resetHandle,
    resetFields,
    downloadTemplateHandle,
    uploadRequest
  };
}
